<template>
  <div class="log-history flex-1 flex flex-col h-0">
    <div class="log-history__header flex justify-between items-center">
      <span class="log-history__header--title">{{$t('custom.syncHistory')}}</span>

      <div class="flex items-center">
        <ejs-daterangepicker :placeholder="$t('custom.marketbot.attenddanceidlereport.search_changedTimeRange')"
                             style=""
                             :format="dateRangeDefaultSetting.format"
                             v-model="searchForm.searchDate"
                             @change="getLogHistorys(1)"
                             :strictMode="dateRangeDefaultSetting.selectionMode">
          <e-presets>
            <e-preset :label="$t('custom.marketbot.clientUsageReport.toDay')"
                      :start='dateRangeDefaultSetting.toDayStartDate'
                      :end='dateRangeDefaultSetting.toDayEndDate'>
            </e-preset>
            <e-preset :label="$t('custom.marketbot.clientUsageReport.thisWeek')"
                      :start='dateRangeDefaultSetting.weekStartDate'
                      :end='dateRangeDefaultSetting.weekEndDate'></e-preset>
            <e-preset :label="$t('custom.marketbot.clientUsageReport.thisMonth')"
                      :start='dateRangeDefaultSetting.monthStartDate'
                      :end='dateRangeDefaultSetting.monthEndDate'></e-preset>

          </e-presets>
        </ejs-daterangepicker>
        <el-select clearable
                   v-model="searchForm.status"
                   @change="getLogHistorys(1)"
                   style="margin-left:15px">
          <el-option v-for="(record,index) in logHistoryStatus"
                     :key="index"
                     :label="$t(`custom.${record.label}`)"
                     :value="record.value"></el-option>
        </el-select>
      </div>

    </div>
    <div style="padding-top: 10px"  v-if="$hasPermission('integration:client-name')">{{$t('custom.tenant.tenantName')}}:{{$store.state.user.tenantName}}</div>

    <div class="log-history__content flex-1 h-0"
         ref="table-wrapper">
      <el-table :data="tableData"
                :height="height"
                row-key="id"
                ref="table"
                :expand-row-keys="expandRowKeys"
                header-cell-class-name="log_history_headers">

        <el-table-column type="expand">
          <template slot-scope="scope">
            <div v-if="scope.row.status === 200">
              <div style="backgroundColor:#EEF5DC;color:#404040;display:flex;padding:8px;">
                <span class="el-icon-circle-check"
                      style="margin-right:8px;color:#67c23a;margin-top:1px"></span>
                <div style="table-layout:fixed; word-break: break-all; overflow:hidden;">API Sync Succeeded.<br>ID:{{scope.row.id}}<br>Params:{{scope.row.params}}</div>
              </div>
            </div>
            <div v-else>
              <div style="backgroundColor:#FFF1F0;color:#404040;display:flex;padding:8px">
                <span class="cuifont icon_info_circle_fill"
                      style="margin-right:8px;color:#b11b0d;margin-top:1px"></span>
                <div style="table-layout:fixed; word-break: break-all; overflow:hidden;">ID:{{scope.row.id}}<br>{{scope.row.msg}}</div>
              </div>
              <div style="margin-left:32px;margin-top:10px"><span style="font-weight:600;color:#404040">How To Fix:</span> If this error was temporary, you can try resubmitting the run and the issue may have been resolved.</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="time"
                         :label="$t('custom.connector.loginfo.startTime')"
                         header-align="center"
                         align="center">
          <template slot-scope="scope">{{ timeAreaFormat(scope.row.time)}}</template>
        </el-table-column>
        <el-table-column prop='elapsed_time'
                         :label="$t('custom.connector.loginfo.mins')"
                         header-align="center"
                         align="center"
                         width="180"></el-table-column>
        <el-table-column prop="status"
                         :label="$t('custom.connector.loginfo.status')"
                         header-align="center"
                         align="center">
          <template slot-scope="scope">
            <div class="table-status"
                 :class="statusStyle(scope.row)">{{getStatus(scope.row)}}</div>
          </template>
        </el-table-column>

      </el-table>
    </div>
    <div class="flex justify-end"
         style="padding:15px 0">
      <el-pagination :page-sizes="[10, 20, 50, 100]"
                     :current-page="pagination.page"
                     :page-size="pagination.limit"
                     :pager-count="5"
                     :total="Number(pagination.total)"
                     layout="total, sizes, prev, pager, next, jumper"
                     @size-change="sizeChange"
                     @current-change="currentChange">
      </el-pagination>
    </div>

  </div>
</template>

<script>
import axios from 'axios'
import { logHistoryStatus } from '../index.data'
// import { getStyle } from 'element-ui/lib/utils/dom';
import moment from 'moment'

export default {
  name: 'LogHistory',
  props: {
    data: {
      type: Object,
      default: () => ({})
    },

    loading: {
      type: Boolean,
      default: false
    }

  },
  data () {
    return {
      logHistoryStatus,
      height: '200px',
      tableData: [
      ],
      pagination: {
        limit: 10,
        page: 1,
        total: 0
      },
      searchForm: {
        searchDate: [],
        api: null,
        status: ''
      },
      expandRowKeys: [],
      selectedLog: {},
      dateRangeDefaultSetting: {
        format: 'yyyy-MM-dd',
        toDayStartDate: moment.tz(moment.utc(), this.$store.state.user.timezoneId).format(),
        toDayEndDate: moment.tz(moment.utc(), this.$store.state.user.timezoneId).format(),
        minDate: new Date('10/1/2019'),
        maxDate: new Date('1/1/2025'),
        weekStartDate: moment().subtract('days', 6).format(),
        weekEndDate: moment().subtract('days', 0).format(),
        monthStartDate: new Date(new Date(new Date().setDate(1)).toDateString()),
        monthEndDate: new Date(new Date(new Date(new Date().setMonth(new Date().getMonth() + 1)).setDate(0)).toDateString())

      }
    }
  },
  created () {
    this.$root.eventBus.$on('event:row-click', (row) => {
      this.selectedLog = row
      this.searchForm.searchDate = [this.dateRangeDefaultSetting.toDayStartDate, this.dateRangeDefaultSetting.toDayEndDate]
      this.getLogHistorys()
    })
  },
  beforeDestroy () {
    this.$root.eventBus.$off('event:row-click')
  },
  mounted () {
    this.getAutoHeight()

    window.onresize = () => {
      this.getAutoHeight()
    }
  },
  watch: {
    loading () {
      this.getAutoHeight()
    }
  },
  methods: {
    getAutoHeight () {
      let el = this.$refs['table-wrapper']

      this.$nextTick(() => {
        if (el) {
          this.height = el.clientHeight
        }
      })
    },
    timeAreaFormat (time) {
      if (time) {
        return moment.tz(time, this.$store.state.user.timezoneId).format('MM/DD/YYYY HH:mm') + ' ' + moment.tz(time, this.$store.state.user.timezoneId).format('zz')
      }
      return time || 0
    },
    statusStyle (row) {
      if (row.status === 200) {
        return 'status_succes'
      }

      return 'status_nosucces'
    },
    getStatus (row) {
      if (row.status === 200) {
        return 'Succeeded'
      }

      return 'Failed'
    },

    sizeChange (val) {
      this.pagination.page = 1
      this.pagination.limit = val
      this.getLogHistorys()
    },
    currentChange (val) {
      this.pagination.page = val
      this.getLogHistorys()
    },
    async getLogHistorys (newPage) {
      if (newPage) {
        this.pagination.page = newPage
      }
      let CancelToken = axios.CancelToken
      const { get, set } = this._
      const { getConnectorLogDetail } = this.$interface.taskManager
      const { status, searchDate } = this.searchForm
      const { limit, page } = this.pagination
      try {
        this.$emit('update:loading', true)
        this.$set(this.selectedLog, 'syncLoading', true)
        const params = {
          tenantId: this.$store.state.user.tenantCode,
          subjectCode: get(this.data, 'sync.subjectCode'),

          interfaceName: get(this.selectedLog, 'action'),
          pageSize: limit,
          page
        }

        if (status !== '') {
          set(params, 'status', status)
        }

        if (searchDate.length >= 2) {
          set(params, 'startTime', moment.tz((moment(searchDate[0]).format('YYYY-MM-DD') + 'T00:00:00'), this.$store.state.user.timezoneId).utc().format())
          set(params, 'endTime', moment.tz((moment(searchDate[1]).add(1, 'days').format('YYYY-MM-DD') + 'T00:00:00'), this.$store.state.user.timezoneId).utc().format())
        }
        let { data: response } = await getConnectorLogDetail(params, {
          cancelToken: new CancelToken(function executor (c) {
            window.getConnectorLogDetail = c
          })
        })

        if (response.code !== 0) {
          throw get(response, 'msg', '')
        }

        this.tableData = get(response, 'data.records', [])
        this.pagination.total = get(response, 'data.total', 0)

        if (this.pagination.total > 0) {
          this.expandRowKeys = this.tableData.filter(i => i.status !== 200).map(i => i.id)
        }
        const allCount = {
          total: get(response, 'data.allTotal', 0),
          successcount: get(response, 'data.successcount', 0)
        }

        this.$root.eventBus.$emit('event:all-count', allCount)
        this.$emit('update:loading', false)
        this.$set(this.selectedLog, 'syncLoading', false)
      } catch (error) {
        if (!axios.isCancel(error)) {
          this.$emit('update:loading', false)
          this.$set(this.selectedLog, 'syncLoading', false)
        }
        // this.$message.error(error)
      } finally {
        // if (!axios.isCancel()) {
        //   this.$emit('update:loading', false)
        //   this.$set(this.selectedLog, 'syncLoading', false)
        // }
      }
    }

  }
}
</script>

<style lang="scss" scoped>
.log-history {
  &__header {
    &--title {
      font-size: 16px;
      color: #404040;
      font-weight: 600;
    }
  }
  &__content {
    margin: 15px 0 0;
    .el-table {
      width: 100%;
      border: 1px solid #ebeef5;
      border-bottom: 0;
    }
    ::v-deep .log_history_headers {
      height: 48px;
      box-shadow: 1px 1px 0px 0px #f0f0f0;
      border-radius: 2px 0px 0px 0px;
      padding: 0;
    }
    .table-status {
      width: 84px;
      height: 24px;
      line-height: 20px;
      margin: 0 auto;
    }
  }
}
.status_succes {
  background: #f0f9eb;
  border-radius: 2px;
  font-size: 14px;
  font-weight: 400;
  color: #67c23a;
  padding: 2px 8px;
}
.status_nosucces {
  background: #fef0f0;
  border-radius: 2px;
  font-size: 14px;
  font-weight: 400;
  color: #f56c6c;
  padding: 2px 8px;
}
.status_warning {
  background: #fef0f0;
  border-radius: 2px;
  font-size: 14px;
  font-weight: 400;
  color: #e6a23c;
  padding: 2px 8px;
}
</style>
